import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, 
    QLabel, QFileDialog, QComboBox, QHBoxLayout
)
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
import serial.tools.list_ports

class ImagePrinterApp(QWidget):
    def __init__(self):
        super().__init__()
        self.selected_image_path = None
        self.preview_layout = None  # 添加这个变量来跟踪预览布局
        self.initUI()

    def initUI(self):
        self.setWindowTitle('黑马嵌入式-图片打印工具')
        self.setGeometry(300, 300, 600, 500)

        layout = QVBoxLayout()

        # 创建串口选择下拉框
        port_layout = QHBoxLayout()
        port_label = QLabel("串口:")
        self.port_combo = QComboBox()
        self.update_ports()
        refresh_button = QPushButton("刷新")
        refresh_button.clicked.connect(self.update_ports)
        
        port_layout.addWidget(port_label)
        port_layout.addWidget(self.port_combo)
        port_layout.addWidget(refresh_button)
        port_layout.addStretch()

        # 创建按钮
        self.open_button = QPushButton('打开图片')
        self.open_button.clicked.connect(self.open_image)
        
        self.print_button = QPushButton('打印图片')
        self.print_button.clicked.connect(self.print_image)
        self.print_button.setEnabled(False)  # 初始时禁用打印按钮

        # 创建预览区域容器
        self.preview_container = QWidget()
        self.preview_container.setMinimumHeight(300)
        self.preview_container.setStyleSheet("border: 1px solid #cccccc;")
        
        # 添加控件到布局
        layout.addLayout(port_layout)
        layout.addWidget(self.open_button)
        layout.addWidget(self.preview_container)
        layout.addWidget(self.print_button)

        self.setLayout(layout)

        self.preview_widget = None  # 添加这个变量来跟踪预览部件

    def update_ports(self):
        """更新可用串口列表"""
        self.port_combo.clear()
        ports = serial.tools.list_ports.comports()
        for port in ports:
            self.port_combo.addItem(f"{port.device} ({port.description})")

    def open_image(self):
        """打开图片文件"""
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择图片",
            "",
            "图片文件 (*.png *.jpg *.bmp);;所有文件 (*)"
        )
        
        if file_name:
            self.selected_image_path = file_name
            
            try:
                # 如果存在旧的预览部件，先删除它
                if self.preview_widget is not None:
                    self.preview_widget.deleteLater()
                
                # 创建新的预览部件
                self.preview_widget = QWidget(self.preview_container)
                preview_layout = QHBoxLayout(self.preview_widget)
                
                # 原图预览
                original_label = QLabel('原图:')
                original_label.setAlignment(Qt.AlignCenter)
                pixmap = QPixmap(file_name)
                scaled_pixmap = pixmap.scaled(
                    self.preview_container.width() // 2,
                    self.preview_container.height(),
                    Qt.KeepAspectRatio,
                    Qt.SmoothTransformation
                )
                original_label.setPixmap(scaled_pixmap)
                
                # 处理后的图片预览
                processed_label = QLabel('处理后:')
                processed_label.setAlignment(Qt.AlignCenter)
                from dither import dither_image
                processed_img = dither_image(file_name, "temp_preview.bmp")
                processed_pixmap = QPixmap("temp_preview.bmp")
                scaled_processed = processed_pixmap.scaled(
                    self.preview_container.width() // 2,
                    self.preview_container.height(),
                    Qt.KeepAspectRatio,
                    Qt.SmoothTransformation
                )
                processed_label.setPixmap(scaled_processed)
                
                # 将两个预览添加到水平布局
                preview_layout.addWidget(original_label)
                preview_layout.addWidget(processed_label)
                
                # 设置新的预览部件的大小和位置
                self.preview_widget.setGeometry(0, 0, self.preview_container.width(), self.preview_container.height())
                self.preview_widget.show()
                
                self.print_button.setEnabled(True)  # 启用打印按钮
            
            except Exception as e:
                from PyQt5.QtWidgets import QMessageBox
                QMessageBox.critical(self, "错误", f"图片处理失败：{str(e)}")

    def print_image(self):
        """打印图片"""
        if not self.selected_image_path:
            return
            
        try:
            # 获取选中的串口
            port = self.port_combo.currentText().split()[0]
            
            # 调用打印功能
            from dither import dither_image, send_to_printer
            img = dither_image(self.selected_image_path, "temp_print.bmp")
            send_to_printer(img, port=port)
            
        except Exception as e:
            from PyQt5.QtWidgets import QMessageBox
            QMessageBox.critical(self, "错误", f"打印失败：{str(e)}")

if __name__ == '__main__':
    print("aaaa")
    app = QApplication(sys.argv)
    ex = ImagePrinterApp()
    ex.show()
    sys.exit(app.exec_())